package cn.xu.study.springdata.hibernatedemo;

import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class HibernateDemo {
    @Test
    public void hibernateTest(){
        //1、实体管理类工厂。其中传递的参数为持久化单元名称，需要jpa配置文件中指定
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
        //2、实体管理类
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        //3、事务对象
        EntityTransaction transaction = entityManager.getTransaction();
        //4、开启事务
        transaction.begin();
        //5、数据库操作
        Customer customer = new Customer();
        customer.setCustName("测试人员");
        entityManager.persist(customer);
        //6、提交事务
        transaction.commit();
        //7、释放资源
        entityManager.close();
        entityManagerFactory.close();
    }

    /*
    添加对象
     */
    @Test
    public void testAdd(){
        EntityManager manager = JPAUtil.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();

        Customer customer = new Customer();
        customer.setCustName("Jack");

        transaction.begin();
        manager.persist(customer);
        transaction.commit();

        manager.close();
    }

    /*
    修改对象
     */
    @Test
    public void testUpdate(){
        EntityManager manager = JPAUtil.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();

        transaction.begin();
        Customer customer = manager.find(Customer.class, 1L);
        customer.setCustAddress("合肥");
        manager.clear();    //???
        manager.merge(customer);
        transaction.commit();

        manager.close();
    }

    /*
    修改对象
     */
    @Test
    public void testRemove(){
        EntityManager manager = JPAUtil.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();

        transaction.begin();
        Customer customer = manager.find(Customer.class, 1L);
        manager.remove(customer);
        transaction.commit();

        manager.close();
    }
}
